package com.k1ccc0.alumniinformationmanagement.controller;

import com.k1ccc0.alumniinformationmanagement.pojo.Administrator;
import com.k1ccc0.alumniinformationmanagement.pojo.Alumni;
import com.k1ccc0.alumniinformationmanagement.pojo.Result;
import com.k1ccc0.alumniinformationmanagement.service.AdministratorService;
import com.k1ccc0.alumniinformationmanagement.service.AlumniService;
import com.k1ccc0.alumniinformationmanagement.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.temporal.TemporalUnit;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@Slf4j

public class LoginController {

    @Autowired
    private AlumniService alumniService;

    @Autowired
    private AdministratorService administratorService;

    //登录验证
    @PostMapping("/Login")
    public Result userLogin(@RequestBody Alumni alumni){
        log.info("用户登录:{}",alumni);
        Alumni a = alumniService.userLogin(alumni);
        //登录成功，生成令牌，下发令牌
        if(a != null){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",a.getId());
            claims.put("name",a.getName());
            claims.put("username",a.getUsername());
            String jwt = JwtUtils.generateJwt(claims);
            return Result.success(jwt);
        }

        //登录失败，返回错误信息
        return Result.error("用户名或密码错误");
    }
    //管理员登录
    @PostMapping("/AdminLogin")
    public Result adminLogin(@RequestBody Administrator administrator){
        log.info("管理员登录:{}",administrator);
        Administrator admin = administratorService.adminLogin(administrator);
        //登录成功，生成令牌，下发令牌
        if(admin != null){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",admin.getId());
            claims.put("name",admin.getName());
            claims.put("username",admin.getUsername());
            String jwt = JwtUtils.generateJwt(claims);
            return Result.success(jwt);
        }

        //登录失败，返回错误信息
        return Result.error("用户名或密码错误");
    }
}
